﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace AktionServer
{
    public class ServerTraad
    {
        private Socket klient;		// socket til klient
        private Monitor monitor;

        public ServerTraad(Socket klient, Monitor monitor)
        {
            this.klient = klient;
            this.monitor = monitor;
        }

        public void HaandterKlient()
        {
            string klientIPadresse, chat;
            NetworkStream networkStream = new NetworkStream(this.klient);
            StreamReader streamReader = new StreamReader(networkStream);
            StreamWriter streamWriter = new StreamWriter(networkStream);


            IPAddress klientIPAdress = ((IPEndPoint)this.klient.RemoteEndPoint).Address;
            klientIPadresse = klientIPAdress.ToString();
            IPHostEntry ip = Dns.GetHostEntry(klientIPAdress);
            Thread.CurrentThread.Name = ip.HostName;

            monitor.AddStreamWriter(streamWriter);	// tilføj streamwriter til monitor

            // Broadcast besked om logon til de andre klienter										
            this.monitor.BroadcastChat(klientIPadresse, "logged on");

            while (true)      // sålænge der kommunikeres med klient
            {
                chat = streamReader.ReadLine();  // Læs chat fra klient
                if (chat == null)
                {
                    break;
                }
                // Broadcast chat til de andre klienter										
                monitor.BroadcastChat(klientIPadresse, chat);
            }

            // fjern streamwriter fra monitor
            monitor.RemoveStreamWriter(streamWriter);

            // Broadcast besked om logoff til de andre klienter										
            monitor.BroadcastChat(klientIPadresse, "logged off");

            Console.WriteLine("Forbindelse til klient lukkes ned...\n");
            streamWriter.Close();
            streamReader.Close();
            networkStream.Close();
        }
    }
}
